package com.kele.system.controller;

import com.github.pagehelper.PageInfo;
import com.kele.base.common.exception.AppException;
import com.kele.base.model.response.ResponseResult;
import com.kele.system.model.dto.RoleDto;
import com.kele.system.model.dto.queryParam.UserListParam;
import com.kele.system.model.entity.Role;
import com.kele.system.model.entity.User;
import com.kele.system.service.RoleService;
import com.kele.system.service.UserService;
import com.kele.system.util.SecurityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.util.StringUtil;

import java.util.List;

/**
 * @Description: 用户信息请求接口
 * @Author: Kele
 * @CreateDate: 2023/4/23 17:56
 * @Version:
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;

    @PostMapping("/getUser")
    public User getUserByUsername(@RequestBody String username){
        User user = userService.getUserByUsername(username);
        return user;
    }

    @PostMapping(value = "/getAuthorities")
    public List<String> getAuthorities(@RequestBody String userId){
        List<String> authorities = userService.getAuthoritiesByUserId(userId);
        return authorities;
    }

    @PostMapping("/getUserList")
    @PreAuthorize("hasAuthority('system-user-list')")
    public ResponseResult getUserList(@RequestBody UserListParam userListParam){
        PageInfo<User> userList = userService.getUserList(userListParam);
        return ResponseResult.success(userList);
    }

    @PostMapping("/addUser")
    @PreAuthorize("hasAuthority('system-user-add')")
    public ResponseResult addUser(@RequestBody User user){
        userService.addUser(user);
        return ResponseResult.success();
    }

    @PostMapping("/getUserRole")
    @PreAuthorize("hasAuthority('system-user-assign-role')")
    public ResponseResult getUserRole(String userId){
        List<RoleDto> result = roleService.getRoleByUserid(userId);
        return ResponseResult.success(result);
    }

    @PostMapping("/assignRole")
    @PreAuthorize("hasAuthority('system-user-assign-role')")
    public ResponseResult assignRole(String userId, List<String> roleIds){
        SecurityUtil.User user = SecurityUtil.getUser();
        if (user == null || StringUtil.isEmpty(user.getId())){
            AppException.cast("请先登录");
        }
        roleService.assignRole(userId, roleIds, user.getId());
        return ResponseResult.success();
    }

}
